from kdecore import KApplication, KCmdLineArgs, KGlobal, KAboutData, KURL
from kdeui import KMainWindow, KMessageBox, KAboutApplication
from kio import KMimeType
from kde.principal import kchmtopdf
from qt import QObject, SIGNAL, QButton, SLOT
import sys
from lib.HTMLParser import HTMLParser
from lib import config
from threading import Thread
import os

def about():
    appName = "kchmtopdf"
    progName = "Kchmtopdf"
    authorNames = ("Heizenreder Guillermo", "Kaufmann Manuel")
    authorEmails = ("gheize@gmail.com", "humitos@gmail.com")
    bugsEmailAddress = "humitos@gmail.com"
    version = "0.3"
    shortDescription = "Convierte archivos .chm a .pdf"
    licenseType = KAboutData.License_GPL
    copyrightStatement = "(c) 2007, %s - %s" % authorNames
    homePageAddress = "http://code.google.com/p/chmtopdf/"
    aboutText = ""
    
    about = KAboutData(
        appName,
        progName,
        version,
        shortDescription,
        licenseType,
        copyrightStatement,
        aboutText,
        homePageAddress,
        bugsEmailAddress)
    for autor, email in zip(authorNames, authorEmails):
        about.addAuthor(autor, "", email)
    return about


class HiloParser(Thread):
    def __init__(self, hmtl, css):
        Thread.__init__(self)
        self.html = html
        self.css = css

    def run():
        if self.css:
            while html.crear_sopa():
                html.buscar_siguiente()
                html.parser_css()
        else:
            while html.crear_sopa():
                html.buscar_siguiente_html()
                html.parser_html()


class GUIFunciones(kchmtopdf):
    def __init__(self, parent=None, name=None, fl=0):
        kchmtopdf.__init__(self, parent, name, fl)
        self.connect_slots()
        self.boton_configurar.setEnabled(False)
        self.libro = dict(etiquetas=config.etiquetas, estilos=config.estilos)

    def connect_slots(self):
        QObject.connect(self.boton_salir, SIGNAL("pressed()"), sys.exit)
        QObject.connect(self.boton_compilar, SIGNAL("pressed()"), self.compilar)
        QObject.connect(self.boton_configurar, SIGNAL("pressed()"), self.configurar)
        QObject.connect(self.checkbox_css, SIGNAL("stateChanged(int)"), self.checkboxcss)
        QObject.connect(self.boton_acerca_de, SIGNAL("pressed()"), self.mostrar_ayuda)

    def mostrar_ayuda(self):
        dlg = KAboutApplication(self)
        dlg.show()

    def compilar(self):
        self.importar_datos()
        if self.datos_validos():
            html = HTMLParser(self.libro)
            print self.libro["titulo"]
            hilo = HiloParser(html, self.libro["css"])
            hilo.setDaemon(False)
            hilo.start()

    def importar_datos(self):
        self.libro["primero"] = str(self.url_primero.url())
        self.libro["siguiente"] = os.path.split(self.libro["primero"])[0]
        self.libro["ultimo"] = str(self.url_ultimo.url())
        self.libro["titulo"] = str(self.linea_titulo.text())
        self.libro["autor"] = str(self.linea_autor.text())
        self.libro["fecha"] = str(self.linea_fecha.text())
        self.libro["css"] = self.checkbox_css.isChecked()
        self.libro["folder"] = str(self.url_guardar_en.url())
        self.libro["imagenes"] = str(self.url_imagenes.url())
        nombre_archivo = self.libro["titulo"].replace(" ", "") + ".tex"
        self.libro["salidatex"] = os.path.join(self.libro["folder"], nombre_archivo)
        #print self.libro

    def configurar(self):
        print "Configurar"

    def checkboxcss(self, state):
        if state:
            self.boton_configurar.setEnabled(True)
        else:
            self.boton_configurar.setEnabled(False)

    def datos_validos(self):
        error = "Uno de los campos de direcciones de archivos es incorrecto."
        for url in ["primero", "ultimo"]:
            url= KURL("file:///%s" % self.libro[url])
            mime = KMimeType.findByURL(url, 0, False, False)
            if mime.name() != "text/html":
                KMessageBox.error(self, error)
                return False
        for url in ["folder", "imagenes"]:
            url= KURL("file:///%s" % self.libro[url])
            mime = KMimeType.findByURL(url, 0, False, False)
            if mime.name() != "inode/directory":
                KMessageBox.error(self, error)
                return False
        return True

if __name__ == "__main__":
    aboutdata = about()
    KCmdLineArgs.init(sys.argv, aboutdata)
    app = KApplication()
    main_window = KMainWindow()
    widget = GUIFunciones(main_window)
    # setea el hijo como widget principal
    main_window.setCentralWidget(widget)
    # sete el tamano de la ventana principal al tamano que tiene el hijo
    main_window.setGeometry(main_window.childrenRect())
    main_window.show()
    app.exec_loop()